package com.wesleyone.wifiusb.common;

import com.jfinal.config.*;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.server.undertow.UndertowServer;
import com.jfinal.template.Engine;
import com.wesleyone.wifiusb.index.IndexController;
import com.wesleyone.wifiusb.util.CommonTools;
import com.wesleyone.wifiusb.util.IpUtil;
import com.wesleyone.wifiusb.util.QRCodeUtil;

import java.io.File;
import java.net.UnknownHostException;


/**
 * @author https://gitee.com/wesleyOne
 */
public class MyConfig extends JFinalConfig {

	static Prop p;
	public static final String FILE_PATH = PathKit.getWebRootPath()+ File.separator +"file";
	public static final String QR_PATH = PathKit.getRootClassPath();
	static final String QR_NAME = "QrCode.png";

	static void loadConfig() {
		if (p == null) {
			p = PropKit.useFirstFound("config.txt");
		}
	}

	public static void main(String[] args) {

		System.out.println(FILE_PATH);
		System.out.println(PathKit.getRootClassPath());
		String hostAddress ;
		try {
			// 动态获取区域网IP
			hostAddress = IpUtil.getLocalHostLANAddress().getHostAddress();
		} catch (UnknownHostException e) {
			System.out.println("获取局域网IP失败："+e.getMessage());
			return;
		}
		System.setProperty("undertow.host",hostAddress);
		UndertowServer.start(MyConfig.class);

		if (System.getProperty("undertow.port") == null){
			System.setProperty("undertow.port","19421");
		}

		try {
			String content = "http://" + hostAddress + ":" + System.getProperty("undertow.port");
			QRCodeUtil.encode(content,null,QR_PATH,QR_NAME, true);
			// 打开登陆二维码图片
			CommonTools.printQr(QR_PATH + File.separator + QR_NAME);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 配置常量
	 */
	@Override
	public void configConstant(Constants me) {
		loadConfig();
		me.setMaxPostSize(1024*1024*1024);
		me.setDevMode(p.getBoolean("devMode"));
	}
	
	/**
	 * 配置路由
	 */
	@Override
	public void configRoute(Routes me) {
		me.add("/", IndexController.class, "/index");
	}

	@Override
	public void configEngine(Engine me) {

	}
	
	/**
	 * 配置插件
	 */
	@Override
	public void configPlugin(Plugins me) {

	}
	
	/**
	 * 配置全局拦截器
	 */
	@Override
	public void configInterceptor(Interceptors me) {
		
	}
	
	/**
	 * 配置处理器
	 */
	@Override
	public void configHandler(Handlers me) {
		
	}

	@Override
	public void onStart() {
		super.onStart();
		// 检查文件夹是否存在
		checkFileExist();
	}

	/**
	 * 检查文件夹(/热登录/下载根目录)是否存在
	 */
	private void checkFileExist() {
		String uploadPath = FILE_PATH;
		File uploadFile = new File(uploadPath);
		if (!uploadFile.exists()){
			if (!uploadFile.mkdirs()) {
				System.out.println("提交文件夹创建失败:"+uploadFile);
			}
		}
	}
}
